//
//  CenterViewController.m
//  SmileWeather
//
//  Created by lanou3g on 15/9/16.
//  Copyright (c) 2015年 陶天海. All rights reserved.
//
#define SIMPLE_SAMPLE NO
#import "CenterViewController.h"
#import "BTGlassScrollView.h"
#import "bouceView.h"
#import "hgcollectionView.h"
#import "HgCollectionViewCell.h"
#import "SHLineGraphView.h"
#import "SHPlot.h"
#import <CoreLocation/CoreLocation.h>
#import "KOMenuView.h"
#import "FortunePaperViewController.h"

NSString *const NewFeatureVersionKey = @"NewFeatureVersionKey";
@interface CenterViewController ()<CLLocationManagerDelegate>
{
    BTGlassScrollView *_glassScrollView;
   UIScrollView *_viewScroller;
    BTGlassScrollView *_glassScrollView1;
    NSUserDefaults *defaluts;
    UICollectionView *collectionView1;
    hgcollectionView *layout;
    TapImageView *tapView;
    Reachability *_hostReachability;//属性
    
}
@property (strong, nonatomic) KOMenuView *blurMenuView;
@property (nonatomic,strong) bouceView *bouce;
@property(nonatomic, strong) CLLocationManager *manager;
@property(nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic,strong) SHLineGraphView *lineGraph;
@property (nonatomic,strong)  SHPlot *plot1;
@property (nonatomic ,strong) MBProgressHUD *hud;
/** 模型数组 */
@property (nonatomic,strong) NSArray *models;

/** scrollView */
@property (nonatomic, strong) UIImageView *image;
@end

@implementation CenterViewController


- (void)p_setupProgressHud
{    [self.hud removeFromSuperview];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    _hud.frame = CGRectMake(kWidth/2-25, kHeight/2-25, 50, 50);
    _hud.minSize = CGSizeMake(50, 50);
    _hud.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_hud];
    
    [_hud show:YES];
}

- (void)relode{
    if (_lineGraph) {
           [_lineGraph removeFromSuperview];
    }
 
   [_hud hide:YES];
    [collectionView1 reloadData];
    _bouce.datimeLab.backgroundColor = [UIColor clearColor];
    _bouce.datimeLab.title.text = [[weatherHandle shareWetherHandle]dateTime];
    _bouce.datimeLab.title.text = [NSString stringWithFormat:@"%@%@",_bouce.datimeLab.title.text,@"更新"];
    [self.view addSubview:_bouce.datimeLab];
//#define mark 折线图
   
  _lineGraph = [[SHLineGraphView alloc] initWithFrame:CGRectMake(0, 0,kWidth, 100)];
//
    NSDictionary *_themeAttributes = @{kXAxisLabelColorKey : [UIColor colorWithRed:0.9 green:0.48 blue:0.49 alpha:1],kXAxisLabelFontKey : [UIFont fontWithName:@"TrebuchetMS" size:10],kYAxisLabelColorKey : [UIColor colorWithRed:0.9 green:0.48 blue:0.1 alpha:1],kYAxisLabelFontKey : [UIFont fontWithName:@"TrebuchetMS" size:10],kYAxisLabelSideMarginsKey : @(-35),kPlotBackgroundLineColorKye : [UIColor clearColor]};
    _lineGraph.themeAttributes = nil;
    _lineGraph.themeAttributes = _themeAttributes;
    
    _lineGraph.yAxisRange = @(40);
    
    _lineGraph.yAxisSuffix = @"℃";
    
    molde *mod= [[weatherHandle shareWetherHandle]arr][0];
    NSString *data = mod.date;
    NSString *temperature = mod.info[@"day"][2];
    molde *mod1= [[weatherHandle shareWetherHandle]arr][1];
    NSString *data1 = mod1.date;
    NSString *temperature1 = mod1.info[@"day"][2];
    molde *mod2= [[weatherHandle shareWetherHandle]arr][2];
    NSString *data2 = mod2.date;
    NSString *temperature2 = mod2.info[@"day"][2];
    molde *mod3= [[weatherHandle shareWetherHandle]arr][3];
    NSString *data3 = mod3.date;
    NSString *temperature3 = mod3.info[@"day"][2];
    molde *mod4= [[weatherHandle shareWetherHandle]arr][4];
    NSString *data4 = mod4.date;
    NSString *temperature4 = mod4.info[@"day"][2];
    molde *mod5= [[weatherHandle shareWetherHandle]arr][5];
    NSString *data5 = mod5.date;
    NSString *temperature5 = mod5.info[@"day"][2];
    molde *mod6= [[weatherHandle shareWetherHandle]arr][6];
    NSString *temperature6 = mod6.info[@"day"][2];
    NSString *data6 = mod6.date;
    
    _lineGraph.xAxisValues = @[@{ @1 : data},@{ @2 : data1 },@{ @3 : data2},@{ @4 : data3 },@{ @5 : data4 },@{ @6 : data5},@{ @7 : data6},];
    
    _plot1 = nil;
     _plot1 = [[SHPlot alloc] init];
    _plot1.plottingValues = @[@{ @1 : temperature },@{ @2 : temperature1},@{ @3 : temperature2},@{ @4 :temperature3 },@{ @5 :temperature4},@{ @6 : temperature5 },@{ @7 : temperature6 },];
//点击方法
NSArray *arr = @[temperature, temperature1, temperature2, temperature3, temperature4, temperature5 , temperature6];
    _plot1.plottingPointsLabels = arr;
//设置主题的属性
NSDictionary *_plotThemeAttributes = @{kPlotFillColorKey : [UIColor colorWithRed:0.47 green:0.75 blue:0.78 alpha:0.5],kPlotStrokeWidthKey : @2,kPlotStrokeColorKey : [UIColor colorWithRed:0.18 green:0.36 blue:0.41 alpha:1],kPlotPointFillColorKey : [UIColor colorWithRed:0.18 green:0.36 blue:0.41 alpha:1],kPlotPointValueFontKey : [UIFont fontWithName:@"TrebuchetMS" size:18]};
    _plot1.plotThemeAttributes = _plotThemeAttributes;
    [_lineGraph addPlot:_plot1];
    [_lineGraph setupTheView];
    
  [_bouce.oneView addSubview:_lineGraph];
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 7;
}
- (NSString *)filePathWithName:(NSString *)fileName {
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(9, 1, 1) lastObject];
    NSLog(@"%@",docPath);
    NSString *filePth = [docPath stringByAppendingPathComponent:fileName];
    return filePth;
    
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        NSArray * arr = [NSArray arrayWithContentsOfFile:[self filePathWithName:@"11.text"]];
      HgCollectionViewCell*cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    NSString *name =  arr[indexPath.row][@"info"][@"day"][1];
    NSString *date1 = arr[indexPath.row][@"date"];
    NSString *week = arr[indexPath.row][@"week"];
    cell.imageView.image =[UIImage imageNamed:[[weatherHandle shareWetherHandle] setWeatherImageName:name]];
    cell.weatherlable.text = date1;
    NSString *string = [NSString stringWithFormat:@"星期%@",week];  cell.weakLab.text = string;
    return cell;
}

- (void)setUpcollectionView{
    
   layout = [[hgcollectionView alloc] init];
    
    // 创建collectionView
    collectionView1 = [[UICollectionView alloc] initWithFrame:CGRectMake(0,200, self.view.frame.size.width, 120) collectionViewLayout:layout];
    collectionView1.dataSource = self;
    collectionView1.delegate = self;
    collectionView1.backgroundColor = [UIColor clearColor];
    collectionView1.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:collectionView1];
    //    self.collectionView = collectionView;
    [collectionView1 registerClass:[HgCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addData];
  [collectionView1 reloadData];
    NSString *remoteHostName = @"www.baidu.com";
       _hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
       [_hostReachability startNotifier];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkStateChange:) name:kReachabilityChangedNotification object:nil];
    
    _weatherTable = [[weatherTableViewController alloc] init];
    [_weatherTable.view setFrame:CGRectMake(30, 40, 200, 0)];
    [_bouce addSubview:_weatherTable.tableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relode) name:@"data" object:nil];
  
     [[weatherHandle shareWetherHandle]relodeData];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //preventing weird insetssta
    [self setAutomaticallyAdjustsScrollViewInsets: NO];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(rightBarButton:)];
    self.navigationItem.rightBarButtonItem = right;
    
    //navigation bar work
    NSShadow *shadow = [[NSShadow alloc] init];
    [shadow setShadowOffset:CGSizeMake(1, 1)];
    [shadow setShadowColor:[UIColor blackColor]];
    [shadow setShadowBlurRadius:1];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor colorWithRed:0.6 green:0.8 blue:0.6 alpha:1], NSShadowAttributeName: shadow};
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
    UIImage * image = [[UIImage imageNamed:@"shouye.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(clickLeft:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.navigationItem.title = @"笑笑天气";
    
    self.view.backgroundColor = [UIColor blackColor];


    self.viewDeckController.panningMode = YES;//设置成没有手势;
    // Do any additional setup after loading the view.
        self.isSelect = YES;
     //   [self setUpcollectionView];

}
  }

- (void)netWorkStateChange:(NSNotification *)note{
    Reachability *curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus) {
        case NotReachable:{
            NSLog(@"网络异常");
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败 请检查网络设置" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [message show];
        }
            break;
        case ReachableViaWWAN:{
            if ([[weatherHandle shareWetherHandle]arr]==0) {
                [[weatherHandle shareWetherHandle] relodeData];
               
            }
            UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您正在使用移动数据请注意您的流量额度" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [message show];
        }
            break;
            
        case ReachableViaWiFi:
            if ([[weatherHandle shareWetherHandle] arr]==0) {
               [[weatherHandle shareWetherHandle] relodeData];
                   }
            break;
        default:
            break;
    }
}

- (void)setLab{
    _blurMenuView = [KOMenuView menuViewWithItem:@[@"                             修改背景"]withPlaceView:self.view withClickByIndex:^(NSInteger itemIndex) {
        NSLog(@"itemIndex : %ld",(long)itemIndex);
        if (itemIndex == 0) {
    FortunePaperViewController *paperVC = [[FortunePaperViewController alloc] init];
    [self transitionWithType:@"cameraIrisHollowOpen" WithSubtype:kCATransitionFromTop ];
    [self.navigationController pushViewController:paperVC animated:YES];
        }
    }];
    _blurMenuView.foldMenuWhenClickItem = YES;
    _blurMenuView.animaDuration = 0.3;
    [self.view addSubview:_blurMenuView];
 }
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_blurMenuView resignFirstResponder];
}
#pragma CATransition动画实现
- (void) transitionWithType:(NSString *) type WithSubtype:(NSString *) subtype
{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    //设置运动时间
    animation.duration = 1.0f;
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
        //设置子类
        animation.subtype = subtype;
    }
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    
    [self.navigationController.view.layer addAnimation:animation forKey:@"animation"];
    
}
- (void)rightBarButton:(UIBarButtonItem *)btn{
   [self.viewDeckController toggleTopView];
}
- (void)addData{
    _bouce = [[bouceView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_bouce];
}
- (void)setBackGrondImage:(NSData*)image{
    if (SIMPLE_SAMPLE) {
             _glassScrollView = [[BTGlassScrollView alloc] initWithFrame:self.view.frame BackgroundImage:[UIImage imageWithData:image] blurredImage:nil viewDistanceFromBottom:120 foregroundView:_bouce];
        
        [self.view addSubview:_glassScrollView];
    }
    else{
        CGFloat blackSideBarWidth = 2;
        
        _viewScroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width + 2*blackSideBarWidth, self.view.frame.size.height+1000)];
        [_viewScroller setPagingEnabled:YES];
        [_viewScroller setDelegate:self];
        [_viewScroller setShowsHorizontalScrollIndicator:NO];
        [self.view addSubview:_viewScroller];
        
        _glassScrollView1 = [[BTGlassScrollView alloc] initWithFrame:self.view.frame BackgroundImage:[UIImage imageWithData:image] blurredImage:nil viewDistanceFromBottom:270 foregroundView:_bouce];
   [_viewScroller addSubview:_glassScrollView1];
        
    }
    [self setLab];
    [self setUpcollectionView];
}
- (void)removeViews{
    [tapView removeFromSuperview];
    [_blurMenuView removeFromSuperview];
    [collectionView1 removeFromSuperview];
    [_glassScrollView1 removeFromSuperview];
    [_viewScroller removeFromSuperview];
    [_glassScrollView removeFromSuperview];
    [_bouce.datimeLab removeFromSuperview];
//    [_bouce removeFromSuperview];
    [_info removeFromSuperview];
    [_relodede removeFromSuperview];
 }
- (void)viewWillAppear:(BOOL)animated
{

    NSData *data= [[NSUserDefaults standardUserDefaults]objectForKey:@"picture"];
   
    if (data) {
        [self removeViews];
        [_relodede removeFromSuperview];
     [self setBackGrondImage:data];
    }
    else{
      [self removeViews];
    NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"53bf4cc93dfae9a0ae000001.jpg"]);
        [self setBackGrondImage:imageData];
    

    }

    if (!_hud) {
       
        [_relodede removeFromSuperview];
        if (data) {
            [self removeViews];
           [self setBackGrondImage:data];
        }
           dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT , 0);
        dispatch_async(queue, ^{
    [self p_setupProgressHud];
      NSLog(@"_____--下载图片1------ %@",[NSThread currentThread]);
          });
}
    if (!SIMPLE_SAMPLE) {
        [tapView removeFromSuperview];
       tapView = [[TapImageView alloc] initWithFrame:CGRectMake(kWidth/1.16,_bouce.frame.size.height*1.0 /15, 20, 20) target:self action:@selector(locations)];
        tapView.image = [UIImage imageNamed:@"location"];
      [_bouce addSubview:tapView];
        [_info removeFromSuperview];
       _info = [[TapImageView alloc] initWithFrame:CGRectMake(kWidth/1.2, _bouce.frame.size.height* 1.0/10.5, 40, 40)target:self action:@selector(infoTap)];
        _info.image = [UIImage imageNamed:@"Entypo_2b(0)_48"];
        [_bouce addSubview:_info];
        [_relodede removeFromSuperview];
       _relodede = [[TapImageView alloc]initWithFrame:CGRectMake(kWidth/1.2, _bouce.frame.size.height*1.0/6.5, 40, 40) target:self action:@selector(relodedate)];
        _relodede.image = [UIImage imageNamed:@"Entypo_d83d(0)_48 2"];
        [_bouce addSubview:_relodede];
        _bouce.datimeLab.backgroundColor = [UIColor clearColor];
        _bouce.datimeLab.title.text = [[weatherHandle shareWetherHandle]dateTime];
        _bouce.datimeLab.title.text = [NSString stringWithFormat:@"%@%@",_bouce.datimeLab.title.text,@"更新"];
        [self.view addSubview:_bouce.datimeLab];
}
       double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
 
});
}
- (void)relodedate{
    [[weatherHandle shareWetherHandle] showHud:self title:@"刷新成功" selector:@selector(weatherRelode) arg:nil targetView:self.view];
    [UIView animateWithDuration:2 animations:^{
        _relodede.transform = CGAffineTransformRotate(_relodede.transform, DEGREES_TO_RADIANS(-179));
    }];
 }
- (void)weatherRelode{
    [[weatherHandle shareWetherHandle] relodeData];
    
}
- (void)infoTap{
    addCityTableViewController *addCityVC = [[addCityTableViewController alloc] initWithStyle:(UITableViewStyleGrouped)];
    addCityVC.navigationItem.title = @"天气设置";
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:addCityVC];
    navVC.navigationBar.barStyle = UIBarStyleBlack;
    [self presentViewController:navVC animated:YES completion:nil];
  
}
- (void)clickLeft:(UIBarButtonItem *)button {
  
    [self.viewDeckController toggleLeftViewAnimated:YES];
}
- (void)viewWillLayoutSubviews
{
    if (SIMPLE_SAMPLE) {
        [_glassScrollView setTopLayoutGuideLength:[self.topLayoutGuide length]];
    }else{
        [_glassScrollView1 setTopLayoutGuideLength:[self.topLayoutGuide length]];
            }
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}

- (BOOL)shouldAutorotate
{
    return YES;
}
- (void)locations{
    [collectionView1 reloadData];
      [self p_setupProgressHud];
    NSLog(@"定位了");
    _manager = [[CLLocationManager alloc]init];
    //判断如果用户没有处理过弹框，就去请求处理
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        //请求在应用程序使用的时候使用定位；
        [_manager requestWhenInUseAuthorization];
    }
    //设置定位的时候精准度，定位越精准就越耗电。
    _manager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置定位的频率（每隔多少米会定位一次）
    _manager.distanceFilter = 1.0;
    _manager.delegate = self;
    //开始定位
    [_manager startUpdatingLocation];
    _geocoder = [[CLGeocoder alloc] init];
    //[self reloadWeather];
    [[weatherHandle shareWetherHandle] relodeData];
}

// 定位成功调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
     //创建一个CLLocation，并获取代理方法传过来的参数。
    CLLocation *location = locations.firstObject;
    NSLog(@"%f, %f", location.coordinate.longitude, location.coordinate.latitude);
        //根据经纬度获取地理位置信息
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = placemarks.firstObject;
        
        NSLog(@"_________%@", placemark.name);
        NSLog(@"--=-=-=-=%@",placemark.locality);
        defaluts=[NSUserDefaults standardUserDefaults];
        NSString *city =[placemark locality];
        [defaluts setObject:city forKey:@"city"];
        [defaluts setObject:[placemark name] forKey:@"place"];
        
    }];
    self.automaticallyAdjustsScrollViewInsets = NO;
     //调用stop方法来关闭定位
    [_manager stopUpdatingLocation];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [UIView animateWithDuration:0.3 animations:^{
        UIButton *btn = (UIButton *)[self.view viewWithTag:2015];
        btn.transform = CGAffineTransformRotate(btn.transform, DEGREES_TO_RADIANS(180));
    }];
      NSArray * arr = [NSArray arrayWithContentsOfFile:[self filePathWithName:@"11.text"]];
       if (self.isSelect) {
                _weatherTable.weatherArray = arr[indexPath.row];
     [self.weatherTable.tableView reloadData];
             _weatherTable.mod = [[weatherHandle shareWetherHandle]arr][indexPath.row];
        [_sectionBtn removeFromSuperview];
        _sectionBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
     [_sectionBtn setBackgroundImage:[UIImage imageNamed:@"down_dark.png"] forState:(UIControlStateNormal)];
        [_sectionBtn addTarget:self action:@selector(sectionBtnTouch:) forControlEvents:UIControlEventTouchUpInside];
        [_bouce addSubview:_sectionBtn];
         }
    [UIView animateWithDuration:0.5 animations:^{
        collectionView.alpha = 0.2;
        collectionView.alpha = 1.0;
        if (self.isSelect == YES) {
            [self setsearchContrlloerHidden:NO];
            self.isSelect = NO;
                }
        else{
            [self setsearchContrlloerHidden:YES];
            self.isSelect = YES;
        }
    }];
 
}
- (void)setsearchContrlloerHidden:(BOOL)hidden{
    NSInteger height = hidden ?0 :180;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [_weatherTable.view setFrame:CGRectMake(0, 36, 200, height)];
    [UIView commitAnimations];
}
- (void)sectionBtnTouch:(UIButton*)btn{
    [UIView animateWithDuration:0.3 animations:^{
        btn.transform = CGAffineTransformRotate(btn.transform, DEGREES_TO_RADIANS(180));
            __block weatherTableViewController *wtvc = _weatherTable;
        //回调刷新
        _weatherTable.block = ^{
            [wtvc.tableView reloadData];
        };
        
    }];
    if (self.isSelect == YES) {
        [self setsearchContrlloerHidden:NO];
        self.isSelect = NO;
        
    }else{
        [self setsearchContrlloerHidden:YES];
        self.isSelect = YES;
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
